<template>
  <div class="product-detail-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item @click="router.push('/')">首页</el-breadcrumb-item>
        <el-breadcrumb-item v-if="product?.categoryName" @click="goToCategory">
          {{ product.categoryName }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ product?.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div v-loading="loading" class="product-container">
      <div v-if="product" class="product-content">
        <!-- 商品图片区域 -->
        <div class="product-images">
          <div class="main-image-container">
            <div class="main-image">
              <el-image
                  :alt="product.name"
                  :preview-src-list="imageList"
                  :src="currentImage"
                  fit="contain"
                  @error="handleImageError"
              />
            </div>
            <!-- 图片指示器 -->
            <div v-if="imageList.length > 1" class="image-indicator">
              {{ currentImageIndex + 1 }} / {{ imageList.length }}
            </div>
          </div>

          <!-- 缩略图列表 -->
          <div v-if="imageList.length > 1" class="image-thumbnails">
            <div
                v-for="(image, index) in imageList"
                :key="index"
                :class="{ active: currentImage === image }"
                class="thumbnail"
                @click="selectImage(image, index)"
            >
              <el-image :src="image" fit="cover" @error="handleImageError"/>
            </div>
          </div>
        </div>

        <!-- 商品信息区域 -->
        <div class="product-info">
          <div class="product-header">
            <h1 class="product-name">{{ product.name }}</h1>
            <p v-if="product.subtitle" class="product-subtitle">{{ product.subtitle }}</p>
          </div>

          <div class="product-price">
            <span class="current-price">¥{{ product.price }}</span>
            <span v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">
              ¥{{ product.originalPrice }}
            </span>
          </div>

          <!-- 商品信息 -->
          <div class="product-info-box">
            <div v-if="product.categoryName" class="info-item">
              <span class="label">分类</span>
              <span class="value">{{ product.categoryName }}</span>
            </div>
            <div v-if="product.brand" class="info-item">
              <span class="label">品牌</span>
              <span class="value">{{ product.brand }}</span>
            </div>
            <div class="info-item">
              <span class="label">销量</span>
              <span class="value">{{ product.sales || 0 }}</span>
            </div>
            <div class="info-item">
              <span class="label">库存</span>
              <span :class="{ 'low-stock': product.stock <= 10 }" class="value">
                {{ product.stock }} 件
              </span>
            </div>
          </div>

          <div class="product-actions">
            <div class="quantity-selector">
              <span class="label">数量：</span>
              <el-input-number
                  v-model="quantity"
                  :disabled="product.stock <= 0"
                  :max="Math.min(99, product.stock)"
                  :min="1"
              />
            </div>

            <div class="action-buttons">
              <el-button
                  :disabled="product.stock <= 0"
                  :loading="addingToCart"
                  size="large"
                  type="primary"
                  @click="addToCart"
              >
                <el-icon>
                  <ShoppingCart/>
                </el-icon>
                {{ product.stock <= 0 ? '暂时缺货' : '加入购物车' }}
              </el-button>

              <el-button
                  :disabled="product.stock <= 0"
                  :loading="buyingNow"
                  size="large"
                  type="danger"
                  @click="buyNow"
              >
                {{ product.stock <= 0 ? '暂时缺货' : '立即购买' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品详情描述 -->
      <div v-if="product" class="product-description">
        <div class="section-title">商品详情</div>
        <div class="description-content" v-html="product.detail || '暂无详细描述'"></div>
      </div>

      <!-- 商品评论 -->
      <div v-if="product" class="product-comments">
        <div class="section-title">
          <span>商品评价</span>
          <span class="comment-count">({{ comments.length }}条评价)</span>
          <!-- 移除独立的写评价按钮，评价功能应该通过订单完成后进行 -->
        </div>

        <div v-if="comments.length > 0" class="comments-list">
          <div
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
          >
            <div class="comment-header">
              <div class="user-info">
                <el-avatar :size="40" :src="comment.userAvatar">
                  <el-icon>
                    <User/>
                  </el-icon>
                </el-avatar>
                <div class="user-details">
                  <span class="username">{{ comment.username }}</span>
                  <div class="rating">
                    <el-rate
                        v-model="comment.rating"
                        disabled
                        score-template="{value}分"
                        show-score
                        text-color="#ff9900"
                    />
                  </div>
                </div>
              </div>
              <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
            </div>

            <div class="comment-content">
              <p>{{ comment.content }}</p>
              <div v-if="comment.images && comment.images.length > 0" class="comment-images">
                <el-image
                    v-for="(image, index) in comment.images"
                    :key="index"
                    :preview-src-list="comment.images"
                    :src="image"
                    class="comment-image"
                    fit="cover"
                />
              </div>
            </div>

            <div v-if="comment.replyContent" class="comment-reply">
              <div class="reply-header">
                <span class="reply-label">商家回复：</span>
                <span class="reply-time">{{ formatDate(comment.replyTime) }}</span>
              </div>
              <p class="reply-content">{{ comment.replyContent }}</p>
            </div>
          </div>
        </div>

        <div v-else class="empty-comments">
          <el-empty description="暂无评价"/>
        </div>
      </div>
    </div>

    <!-- 商品不存在 -->
    <div v-if="!loading && !product" class="product-not-found">
      <el-empty description="商品不存在或已下架">
        <el-button type="primary" @click="goBack">返回</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {ShoppingCart} from '@element-plus/icons-vue'
import {getProductDetail} from '@/api/product'
import {getProductComments} from '@/api/comment'
import {addToCart as addToCartApi} from '@/api/cart'
import {useCartStore, useUserStore} from '@/store'
import {formatDate} from '@/utils'

// 路由相关
const router = useRouter()
const route = useRoute()

// 状态管理
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const loading = ref(false)
const product = ref(null)
const comments = ref([])
const quantity = ref(1)
const addingToCart = ref(false)
const buyingNow = ref(false)
const currentImage = ref('')
const currentImageIndex = ref(0)

// 计算属性
const imageList = computed(() => {
  if (!product.value) return []

  const images = []
  // 添加主图
  if (product.value.mainImage) {
    images.push(product.value.mainImage)
  }
  // 添加子图（后端已经返回数组格式）
  if (product.value.subImages && Array.isArray(product.value.subImages)) {
    images.push(...product.value.subImages)
  }
  return images
})

// 删除不再使用的子图列表计算属性

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    loading.value = true
    const productId = route.params.id

    const response = await getProductDetail(productId)
    product.value = response.data

    // 设置默认显示图片
    if (imageList.value.length > 0) {
      currentImage.value = imageList.value[0]
      currentImageIndex.value = 0
    }

    // 获取商品评论
    await fetchComments()
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 获取商品评论
const fetchComments = async () => {
  try {
    const productId = route.params.id
    if (!productId) return

    console.log('获取商品评论:', productId)
    const response = await getProductComments(productId, {
      current: 1,
      size: 10
    })

    console.log('评论数据:', response)
    if (response && response.data && response.data.records) {
      // 处理评论数据格式
      comments.value = response.data.records.map(comment => ({
        ...comment,
        // 处理图片数据
        images: comment.images ? (typeof comment.images === 'string' ? JSON.parse(comment.images) : comment.images) : [],
        // 处理用户名显示（匿名处理）
        username: comment.isAnonymous ? '匿名用户' : (comment.username || '用户***')
      }))
    } else {
      comments.value = []
    }
  } catch (error) {
    console.error('获取商品评论失败:', error)
    comments.value = []
  }
}

// 加入购物车
const addToCart = async () => {
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    addingToCart.value = true

    await addToCartApi({
      productId: product.value.id,
      quantity: quantity.value
    })

    ElMessage.success('已加入购物车')
    // 更新购物车统计
    await cartStore.fetchCartSummary()
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  } finally {
    addingToCart.value = false
  }
}

// 立即购买
const buyNow = async () => {
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (quantity.value > product.value.stock) {
    ElMessage.warning('购买数量不能超过库存')
    return
  }

  try {
    buyingNow.value = true

    // 构造立即购买的商品数据
    const buyNowItem = {
      id: `buy_now_${product.value.id}`, // 临时ID
      productId: product.value.id,
      productName: product.value.name,
      productImage: product.value.mainImage,
      currentPrice: product.value.price,
      quantity: quantity.value,
      subtotal: (product.value.price * quantity.value).toFixed(2),
      stock: product.value.stock,
      productStatus: product.value.status,
      selected: true
    }

    // 跳转到结算页面，传递立即购买的商品信息
    router.push({
      path: '/checkout',
      query: {
        items: JSON.stringify([buyNowItem]),
        type: 'buyNow' // 标识为立即购买
      }
    })
  } catch (error) {
    console.error('立即购买失败:', error)
    ElMessage.error('立即购买失败')
  } finally {
    buyingNow.value = false
  }
}


// 选择图片
const selectImage = (image, index) => {
  currentImage.value = image
  currentImageIndex.value = index
}

// 删除不再使用的图片导航函数

// 处理图片加载错误
const handleImageError = (e) => {
  console.error('图片加载失败:', e)
  // 可以设置默认图片
  // e.target.src = '/placeholder.jpg'
}

// 跳转到分类页面
const goToCategory = () => {
  if (product.value?.categoryId) {
    router.push(`/category/${product.value.categoryId}`)
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProductDetail()
})
</script>

<style scoped>
.product-detail-page {
  background: var(--bg-secondary);
  min-height: 100vh;
}

/* 面包屑导航 */
.breadcrumb-container {
  background: var(--bg-card);
  padding: 1rem 0;
  border-bottom: 1px solid var(--border-light);
  box-shadow: var(--shadow-sm);
}

.breadcrumb-container .el-breadcrumb {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1.5rem;
}

.breadcrumb-container .el-breadcrumb-item {
  cursor: pointer;
}

.product-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

/* 商品内容区域 */
.product-content {
  display: grid;
  grid-template-columns: 1.2fr 1fr;
  gap: 3rem;
  background: var(--bg-card);
  padding: 2rem;
  border-radius: var(--radius-2xl);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 商品图片区域 */
.product-images {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.main-image-container {
  position: relative;
  width: 100%;
  height: 500px;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.main-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.main-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.image-indicator {
  position: absolute;
  bottom: 15px;
  right: 15px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
}

.image-thumbnails {
  display: flex;
  gap: 12px;
  overflow-x: auto;
  padding: 10px 0;
  scrollbar-width: thin;
}

.image-thumbnails::-webkit-scrollbar {
  height: 6px;
}

.image-thumbnails::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.image-thumbnails::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.image-thumbnails::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: var(--radius-lg);
  overflow: hidden;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
  background: var(--bg-card);
  box-shadow: var(--shadow-sm);
}

.thumbnail:hover {
  border-color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.thumbnail.active {
  border-color: var(--primary-color);
  box-shadow: 0 4px 12px var(--primary-300);
}

.thumbnail .el-image {
  width: 100%;
  height: 100%;
}

/* 商品信息框样式 */
.product-info-box {
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.info-item .label {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.info-item .value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.info-item .value.low-stock {
  color: #f56c6c;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 商品信息区域 */
.product-info {
  display: flex;
  flex-direction: column;
  gap: 25px;
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  line-height: 1.3;
}

.product-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
  line-height: 1.6;
  background: #f8f9fa;
  padding: 10px 15px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 15px;
  padding: 20px;
  background: linear-gradient(135deg, #fff5f5 0%, #fff8f8 100%);
  border-radius: 12px;
  border: 1px solid #fde2e2;
}

.current-price {
  font-size: 32px;
  font-weight: 700;
  color: #e53e3e;
  text-shadow: 0 1px 2px rgba(229, 62, 62, 0.1);
}

.original-price {
  font-size: 18px;
  color: #909399;
  text-decoration: line-through;
  position: relative;
}

.original-price::before {
  content: '原价：';
  font-size: 12px;
  color: #909399;
  margin-right: 4px;
}

/* 旧样式已删除，使用新的product-info-box样式 */

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 25px;
  padding: 25px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
  border: 1px solid #e4e7ed;
}

.quantity-selector .label {
  color: #606266;
  font-weight: 600;
  font-size: 16px;
  min-width: 60px;
}

.quantity-selector .el-input-number {
  width: 120px;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.action-buttons .el-button {
  flex: 1;
  height: 55px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

/* 商品详情描述 */
.product-description,
.product-comments {
  background: white;
  padding: 35px;
  border-radius: 12px;
  margin-bottom: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 3px solid #409eff;
  display: flex;
  align-items: center;
  gap: 10px;
  justify-content: space-between;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -3px;
  left: 0;
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #409eff, #67c23a);
  border-radius: 2px;
}

.comment-count {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
}

.description-content {
  line-height: 1.8;
  color: #606266;
}

/* 评论列表 */
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.comment-item {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.comment-time {
  color: #909399;
  font-size: 14px;
}

.comment-content p {
  margin: 0 0 15px 0;
  line-height: 1.6;
  color: #606266;
}

.comment-images {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.comment-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.comment-reply {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reply-label {
  font-weight: 500;
  color: #409eff;
}

.reply-time {
  color: #909399;
  font-size: 12px;
}

.reply-content {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

.empty-comments {
  text-align: center;
  padding: 40px 20px;
}

.product-not-found {
  background: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
}

/* 响应式设计 */
/* 平板端 */
@media (max-width: 1024px) {
  .product-content {
    grid-template-columns: 1fr 1fr;
    gap: 30px;
  }

  .main-image-container {
    height: 400px;
  }

  .thumbnail {
    width: 80px;
    height: 80px;
  }
}

/* 移动端 */
@media (max-width: 768px) {
  .product-container {
    padding: 10px;
  }

  .breadcrumb-container .el-breadcrumb {
    padding: 0 10px;
    font-size: 12px;
  }

  .product-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .main-image-container {
    height: 350px;
  }

  .product-info {
    padding: 15px;
  }

  .product-header h1 {
    font-size: 20px;
    line-height: 1.4;
  }

  .product-header p {
    font-size: 13px;
  }

  .current-price {
    font-size: 24px;
  }

  .original-price {
    font-size: 14px;
  }

  .product-info-box {
    padding: 12px;
  }

  .info-item {
    font-size: 13px;
  }

  .quantity-selector {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    padding: 15px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }

  .action-buttons .el-button {
    height: 45px;
    font-size: 14px;
  }

  .thumbnail {
    width: 60px;
    height: 60px;
  }

  .product-description,
  .product-comments {
    padding: 15px;
  }

  .section-title {
    font-size: 16px;
  }

  .comment-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}

/* 小屏手机 */
@media (max-width: 480px) {
  .product-container {
    padding: 5px;
  }

  .breadcrumb-container .el-breadcrumb {
    padding: 0 8px;
    font-size: 11px;
  }

  .main-image-container {
    height: 280px;
  }

  .product-info {
    padding: 12px;
  }

  .product-header h1 {
    font-size: 18px;
  }

  .product-header p {
    font-size: 12px;
  }

  .current-price {
    font-size: 22px;
  }

  .original-price {
    font-size: 13px;
  }

  .product-info-box {
    padding: 10px;
  }

  .info-item {
    font-size: 12px;
  }

  .quantity-selector {
    padding: 12px;
  }

  .action-buttons .el-button {
    height: 40px;
    font-size: 13px;
  }

  .thumbnail {
    width: 50px;
    height: 50px;
  }

  .product-description,
  .product-comments {
    padding: 12px;
  }

  .section-title {
    font-size: 15px;
  }

  .comment-item {
    padding: 12px;
  }

  .comment-content {
    font-size: 13px;
  }

  .comment-meta {
    font-size: 11px;
  }

  .product-header h1 {
    font-size: 20px;
  }

  .current-price {
    font-size: 24px;
  }

  .product-info-box {
    padding: 12px;
  }

  .quantity-selector {
    padding: 12px;
  }

  .thumbnail {
    width: 60px;
    height: 60px;
  }

  .product-description,
  .product-comments {
    padding: 15px;
  }

  .section-title {
    font-size: 16px;
  }
}
</style>
